
package com.filetransfer.server.fileserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.filetransfer.client.state.ServerReceiveControl;
import com.filetransfer.config.FileServerConfig;


/**
 * 功能说明: <br>
 * 开发人员: hanxuetong <br>
 * 开发时间: 2014-7-25 <br>
 * 审核人员: <br>
 * 相关文档: <br>
 * 修改记录: <br>
 * 修改日期 修改人员 修改说明 <br>
 * ======== ====== ============================================ <br>
 * 
 */
public class FileReceiveServer {

	// private int bindPort = GlobalProperties.B_RECEIVE_FILE_PORT;
	// //默认监听端口号为10000
	// private int tryBindTimes = 0; //初始的绑定端口的次数设定为0
	private ServerSocket serverSocket; // 服务套接字等待对方的连接和文件发送
	private ExecutorService executorService; // 线程池
	// private final int POOL_SIZE = 4; //单个CPU的线程池大小
	// private String
	// receiveFileSavePath=GlobalProperties.RECEIVE_FILE_SAVE_PATH;

	private ServerReceiveControl serverReceiveControl;

	/**
	 * 不带参数的构造器，选用默认的端口号
	 * 
	 * @throws Exception
	 */
	public FileReceiveServer(ServerReceiveControl serverReceiveControl)
			throws Exception {

		if (serverReceiveControl == null) {
			throw new Exception("文件服务器 fileServerConfig 不能为空！");
		}
		this.serverReceiveControl = serverReceiveControl;
		try {
			this.bingToServerPort(serverReceiveControl.getFileServerConfig().getReceiveFilePort());
			creatThreadPool();
		} catch (Exception e) {
			throw new Exception("绑定端口不成功!");
		}
	}

	private void creatThreadPool() {
		// executorService =
		// Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()
		// * POOL_SIZE);
		executorService = Executors.newFixedThreadPool(serverReceiveControl.getFileServerConfig()
				.getPoolSize());
		System.out.println("开辟线程数 ： " + serverReceiveControl.getFileServerConfig().getPoolSize());
	}


	public void service() {

		Socket socket = null;
		while (true) {
			try {
				socket = serverSocket.accept();
				System.out.println("socket接收！！");
				executorService.execute(new ReceiveFileHandle(socket,
						serverReceiveControl));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void bingToServerPort(int port) throws Exception {
		try {
			serverSocket = new ServerSocket(port);

			System.out.println("文件接收服务启动! 端口为" + port);
		} catch (Exception e) {
			/*
			 * this.tryBindTimes = this.tryBindTimes + 1; port = port +
			 * this.tryBindTimes; if(this.tryBindTimes >= 10){ throw new
			 * Exception("您已经尝试很多次了，但是仍无法绑定到指定的端口!请重新选择绑定的默认端口号"); } //递归绑定端口
			 * this.bingToServerPort(port);
			 */
			com.filetransfer.util.LogUtil.err("启动信息接收服务失败，端口"
					+ port + "被占用！", e);
			 throw new RuntimeException("启动信息接收服务失败，端口"
					+ port + "被占用！");

		}
	}

	public static void main(String[] args) {
	/*	FileReceiveServer ser;
		try {
			ser = new FileReceiveServer();
			ser.service();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

	}

}
